const axios = require('axios');
const randomUseragent = require('random-useragent');
const global = require('./global');
const helper = require('./helper');
const contentLogic = require('../business-logic/content');
const email = require('../email/email');

function getCrawlerOptions(site, keyword) {
    let options = {
        method: site.method,
        uri: site.url,
        headers: {
            'Content-Type': 'application/x-www-form-urlencoded',
            'Origin': site.origin,
            'User-Agent': randomUseragent.getRandom()
        },
        callback: callbackFactory(site, keyword)
    }
    if (site.method.toUpperCase() === 'POST') {
        options.body = getPostBody(site, keyword);
    }
    if (site.type === 'weixin') {
        options.uri = `http://weixin.sogou.com/weixin?type=1&query=${encodeURI(site.weixinName)}`
        options.headers['Referer'] = `http://weixin.sogou.com/weixin?type=1&query=${encodeURI(site.weixinName)}`;
        options.headers['Host'] = 'weixin.sogou.com';
    }
    if (site.type === 'weibo') {
        options.uri = `https://m.weibo.cn/profile/info?uid=` + site.weiboId;
        options.jQuery = false;
    }
    return options;
}

function getPostBody(site, keyword) {
    let body = site.key + '=' + keyword.words.join(' ');
    if (site.channelId) {
        // body = body + '&channelid=' + site.channelId;
        body = `${body}&${site.channelId}`
    }
    return body;
}

function addContentInfo(contents, site, keyword) {
    for (const content of contents) {
        content.siteId = site.id;
        content.keywordId = keyword.id;
        content.keywords = keyword.words.join(' ');
        content.siteName = site.siteName;
    }
}

function callbackFactory(site, keyword) {
    let callback;
    switch (site.type) {
        case 'zhgov':
            callback = function(err, res, done) {
                if (err) {
                    return global.errorHandler(err);
                }
                let $ = res.$;
                let $contents = $(site.contentSelector);
                if ($contents.length) {
                    let contents = helper.parsingGovContents($contents, $, site.url);
                    contents = helper.filterContent(contents, keyword.words);
                    addContentInfo(contents, site, keyword);
                    contentLogic.saveContents(contents, site.id, keyword.id)
                        .then(saved => {
                            if (saved.length) {
                                email.queue(keyword.emails, saved);
                            }
                            email.eventEmitter.emit('send');
                        })
                }
                done();
            }
            break;
        case 'weibo':
            callback = function(err, res, done) {
                if (err) {
                    return global.errorHandler(err);
                }
                let body = JSON.parse(res.body);
                let contents = body.data.statuses.map(item => {
                    return {
                        keywordId: keyword.id,
                        siteId: site.id,
                        date: item.created_at,
                        weibo: item,
                        title: helper.removeHTML(item.text),
                        link: 'https://m.weibo.cn/detail/' + item.mid,
                        keywords: keyword.words.join(' ')
                    }
                });

                contents = helper.filterContent(contents, keyword.words, 'weibo');
                addContentInfo(contents, site, keyword);

                contentLogic.saveContents(contents)
                    .then(saved => {
                        if (saved.length) {
                            email.queue(keyword.emails, saved);
                        }
                        email.eventEmitter.emit('send');
                    })

                done();
            }
            break;
        case 'weixin':
            callback = function(err, res, done) {
                let $ = res.$;

                let $weixinAccounts = $('.news-list2 li');
                if ($weixinAccounts.length) {
                    let $target = $weixinAccounts.eq(0);
                    let url = $target.find('[uigs="account_name_0"]').attr('href');
                    axios.get(url)
                        .then(res => {
                            let data = res.data;
                            let regexp = /var\smsgList\s=\s(\{.+\});\n/
                            let result = regexp.exec(data);
                            if (!result) {
                                console.log('请输入验证码')
                                return;
                            }
                            let weixinData = JSON.parse(result[1]);

                            let contents = helper.parsingWeixinContents(weixinData.list);
                            contents = helper.filterContent(contents, keyword.words, 'weixin');
                            addContentInfo(contents, site, keyword);
                            contentLogic.saveContents(contents)
                                .then(saved => {
                                    if (saved.length) {
                                        email.queue(keyword.emails, saved);
                                    }
                                    email.eventEmitter.emit('send');
                                })
                        })
                } else {
                    console.log('请输入验证码');
                }
                done();
            }
            break;
        default:
            callback = function(err, res, done) { done(); };
            break;
    }
    return function(err, res, done) {
        try {
            callback(err, res, done);
        } catch (error) {
            done();
        }
    };
}

module.exports = {
    getCrawlerOptions,
    getPostBody,
    callbackFactory
}